﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Main : MonoBehaviour
{
    public int SizeX;
    public int SizeY;
    public int ObjectNums;

    public UnityEngine.UI.RawImage TileImageTemplate;
    UnityEngine.UI.RawImage[] TileImages;

    Dictionary<Dungeon.Tile, Texture2D> TileTextureDictionary = new Dictionary<Dungeon.Tile, Texture2D>();

    [System.Serializable]
    public struct TileTexturePair
    {
        public Dungeon.Tile tile;
        public Texture2D tex;
    }
    public TileTexturePair[] TileTextures;

    Dungeon dungeon = new Dungeon();

    // Start is called before the first frame update
    void Start()
    {
        for (int i = 0; i < TileTextures.Length; i++)
            TileTextureDictionary[TileTextures[i].tile] = TileTextures[i].tex;

        PrepareImage();


        ReGenerateDungeon();
    }

    public void ReGenerateDungeon()
    {
        dungeon.CreateDungeon(SizeX, SizeY, ObjectNums);
        DisplayRoomImages();
    }

    void PrepareImage()
    {
        float TileImageWidth = TileImageTemplate.rectTransform.rect.width;
        float TileImageHeight = TileImageTemplate.rectTransform.rect.height;
        TileImages = new UnityEngine.UI.RawImage[SizeX*SizeY];
        for (int x = 0; x < SizeX; x++)
            for (int y = 0; y < SizeY; y++)
            {
                int index = x + SizeX * y;
                TileImages[index] = Instantiate(TileImageTemplate.gameObject).GetComponent<UnityEngine.UI.RawImage>();
                TileImages[index].rectTransform.SetParent(TileImageTemplate.rectTransform.parent);
                TileImages[index].rectTransform.anchoredPosition = new Vector2((1.0f * x - 0.5f * SizeX + 0.5f) * TileImageWidth, (1.0f * y - 0.5f * SizeY + 0.5f) * TileImageHeight);
            }
        TileImageTemplate.gameObject.SetActive(false);
    }

    //显示出房间图片
    void DisplayRoomImages()
    {
        var dg = dungeon.GetDungeon();

        for (int x = 0; x < SizeX; x++)
            for (int y = 0; y < SizeY; y++)
            {
                int index = x + SizeX * y;
                TileImages[index].texture = TileTextureDictionary[dg[index]];
            }      
    }


    // Update is called once per frame
    void Update()
    {
        
    }
}
